package com.lineng.util;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionListener implements HttpSessionListener {

	public static HashMap<String, String> userMap = new HashMap<String, String>();

	public static HashMap<String, HttpSession> sessionMap = new HashMap<String, HttpSession>();

	public void sessionCreated(HttpSessionEvent httpSessionEvent) {

	}

	public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
		HttpSession session = httpSessionEvent.getSession();
		String sessionId = session.getId();
		sessionMap.remove(sessionId);
		for (String key : userMap.keySet()) {
			if (userMap.get(key).equals(sessionId)) {
				userMap.remove(key);
			}
		}
	}

	public static void checkUser(String username, HttpServletRequest request) {
		// 用户登录成功后，更新session Map，如重复登录，强制之前session过期
		String sessionid = SessionListener.userMap.get(username);
		if (sessionid != null && !sessionid.equals("")) {
			// 注销在线用户,如果session id 相同，不销毁。
			if (!sessionid.equals(request.getSession().getId())) {
				SessionListener.sessionMap.get(sessionid).invalidate();
				SessionListener.userMap.put(username, request.getSession().getId());
				SessionListener.sessionMap.put(request.getSession().getId(), request.getSession());
			}
		} else {
			if (SessionListener.sessionMap.containsKey(request.getSession().getId())) {
				SessionListener.sessionMap.remove(request.getSession().getId());
				for (String key : SessionListener.userMap.keySet()) {
					if (SessionListener.userMap.get(key).equals(request.getSession().getId())) {
						SessionListener.userMap.remove(key);
					}
				}
			}

			SessionListener.userMap.put(username, request.getSession().getId());
			SessionListener.sessionMap.put(request.getSession().getId(), request.getSession());

		}

	}
}
